package com.sky.controller;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.InstructorLoginDTO;
import com.sky.entity.Instructor;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserLoginService;
import com.sky.utils.JwtUtil;
import com.sky.vo.InstructorInfoVO;
import com.sky.vo.InstructorLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.sky.context.BaseContext.removeCurrentId;

@RestController
@Slf4j
@RequestMapping("/api/sys")
public class UserController {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    public Result<InstructorLoginVO> login (@RequestBody @Valid InstructorLoginDTO instructorLoginDTO) {
        Instructor instructor = userLoginService.login(instructorLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, instructor.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        // 获取当前启动ID, 记录当前用户的id
        String startupId = (String) redisTemplate.opsForValue().get("jwt:startup-id");
        String key = "jwt:whitelist:" + startupId + instructor.getId();
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.DAYS);
        // 清理redis中用户未激活的标识
        redisTemplate.delete("instructor:time:" + instructor.getId());

        InstructorLoginVO instructorLoginVO = InstructorLoginVO.builder()
                .id(instructor.getId())
                .name(instructor.getName())
                .token(token)
                .build();
        return Result.success(instructorLoginVO, MessageConstant.LOGIN_OK);
    }
    /**
     * 用户登出
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(@RequestBody Map<String, String> body) {
        String userId = body.get("userId");
            // 2. 获取启动 ID
            String startupId = (String) redisTemplate.opsForValue().get("jwt:startup-id");
            if (startupId != null) {
                String key = "jwt:whitelist:" + startupId + userId;
                Boolean removed = redisTemplate.delete(key);
            } else {
                log.warn("登出操作：未能获取 startup-id，跳过 Redis 清理");
            }
        return Result.success(null,MessageConstant.OK_MESSAGE);
    }

    /**获取教师姓名 id 参数*/
    @GetMapping("/getUserName")
    public Result<List<Map<String, Object>>> getUserName(@RequestParam("name") String name) {
        log.info("获取用户姓名和id，模糊查询参数：{}", name);
        List<Map<String, Object>> users = userLoginService.getUserName(name);
        return Result.success(users, MessageConstant.OK_MESSAGE);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public Result<InstructorInfoVO> getUserInfo() {
        String userId = BaseContext.getCurrentId();
        log.info("获取用户信息，用户id：{}", userId);
        InstructorInfoVO instructor = userLoginService.getUserInfo(userId);
        return Result.success(instructor, MessageConstant.OK_MESSAGE);
    }
    /**判断用户信息是否完整*/
    @GetMapping("/isUserInfoComplete")
    public Result<Boolean> isUserInfoComplete() {
        String userId = BaseContext.getCurrentId();
        InstructorInfoVO instructor = userLoginService.getUserInfo(userId);
        boolean isComplete = isInstructorInfoComplete(instructor);
        return Result.success(isComplete);
    }

    /**
     * 判断教师信息是否完整
     * @param instructor
     * @return
     */
    private boolean isInstructorInfoComplete(InstructorInfoVO instructor) {
        if (instructor == null) return false;
        int notNullCount = 0;
        for (Field field : instructor.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                Object value = field.get(instructor);
                if (value != null) {
                    // 可选：如果是字符串类型，排除空字符串
                    if (value instanceof String && ((String) value).trim().isEmpty()) {
                        continue;
                    }
                    notNullCount++;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return notNullCount >= 14;
    }

    /**
     * 获取手机验证码
     * @param map 包含手机号的Map
     * @return
     * @throws IOException
     */
    @PostMapping("/getPhoneCode")
    public Result<String> getPhoneCode(@RequestBody Map<String, String> map) throws IOException {
        String phone = map.get("phone");
        // 手机号验证
        if (phone == null || !phone.matches("^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[1589]))\\d{8}$")) {
            return Result.error("手机号格式不正确");
        }
        String result = userLoginService.getPhoneCode(phone);
        return Result.success(null, result);
    }
}
